import Store from './store'

const path = require('path')
const fs = require('fs')
const os = require('os')
const userDir = os.homedir()
const documentsFolder = path.join(userDir, '/Documents')
const sweetCircleFilesFolder = path.join(documentsFolder, '/SweetCircleFiles')

const express = require('express')
const { exec } = require('child_process')
const app = express()
let port = 2024

/**
 * 递归创建目录，确保路径中的所有目录都存在。
 * 如果目录已经存在，则不进行任何操作。
 *
 * @param {string} dir - 需要创建的目录路径。
 * @returns {void} - 该函数没有返回值。
 */
const mkdirs = (dir) => {
  // 检查目录是否已经存在
  if (!fs.existsSync(dir)) {
    // 获取当前目录的上级目录
    const parentDir = path.dirname(dir)

    // 确保当前目录不是根目录，避免无限递归
    if (parentDir !== dir) {
      // 递归创建上级目录
      mkdirs(parentDir)
    }

    // 创建当前目录
    fs.mkdirSync(dir)
  }
}

app.get('/test', (req, res) => {
  res.send('test')
})

app.get('/image', (req, res) => {
  const userDataFolder = path.join(sweetCircleFilesFolder, `/sc_${Store.getUserId()}`)
  let { filename,sessionId } = req.query
  const fileSuffix = filename.split('.').pop()
  res.setHeader('Access-Control-Allow-Origin', '*')
  res.setHeader('Content-Type', `image/${fileSuffix}`)
  let imagePath = path.join(userDataFolder, `/Files/images`,`/${sessionId}`)
  mkdirs(imagePath)
  let filepath = path.join(imagePath, filename)
  fs.createReadStream(filepath).pipe(res)
})
app.get('/video', (req, res) => {
  const userDataFolder = path.join(sweetCircleFilesFolder, `/sc_${Store.getUserId()}`)
  let { filename,sessionId } = req.query
  res.setHeader('Access-Control-Allow-Origin', '*')
  res.setHeader('Content-Type', 'video/mp4')
  let videoPath = path.join(userDataFolder, `/Files/videos`,`/${sessionId}`)
  mkdirs(videoPath)
  let filepath = path.join(videoPath, filename)
  fs.createReadStream(filepath).pipe(res)
})

let server = null

const checkPort = () => {
  exec(`netstat -aon | findstr "${port}"`, (error, stdout) => {
    if (error) {
      server = app.listen(port, () => {
        console.log(`express 启动成功 端口 ${port}`)
        Store.setExpressPort(port)
      })
      return
    }
    if (stdout.trim()) {
      port += 1
    }
    checkPort()
  })
}

const startLocalServer = () => {
  checkPort()
}

const closeLocalServer = () => {
  server.close()
  console.log('server close')
}

export default {
  startLocalServer,
  closeLocalServer
}
